package com.itboye.ihomebank.activity.hetong;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.mobileim.lib.model.message.IFileMessage;
import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.qianyue.fragment.OrderFragment;
import com.itboye.ihomebank.adapter.HeTongAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.HeTongBean;
import com.itboye.ihomebank.bean.HetongCaoGao;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.db.HeTongDBManager;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.DayCountTwo;
import com.itboye.ihomebank.util.FuKuanFangShiPopupWindow;
import com.itboye.ihomebank.util.MyGongJv;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.util.YuYueChooseTimePopwindow;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 修改合同
 */
public class ActivityEditHeTongFangdong extends BaseOtherActivity implements
		Observer , YuYueChooseTimePopwindow.onFinishedLisenter{
	View v_statusbar;
	TextView add_shap_title_tv;
	ImageView close_icon;
	private String contractNo;
	private String uid;
	private UserPresenter userPresenter;
	private ArrayList<TextView> devices = new ArrayList<>();
	private Calendar current = Calendar.getInstance(Locale.CHINA);
	private ArrayList<EditText> editTexts = new ArrayList<>();
	private LinearLayout li_container;
	private ArrayList<View> views = new ArrayList<View>();
	protected String yajin;
	protected int selectEndYear;
	protected int selectStartYear;
	protected int qishu;
	private int selectStartMonth;
	private int selectEndMonth;
	HeTongDBManager heTongDBManager;
	private HetongCaoGao caoGao;
	private String selectDevice;
	private String selectFeiYong;
	private String unselectFeiYong;
	private String zujinxinxi="";//租金信息
	private String imgId="";//签名图片id
	Button tijiao;
	private HeTongDBManager dbManager;
	protected String tempStartTimes;
	protected String tempEndTimes;
	protected FuKuanFangShiPopupWindow mCameraPopupWindow;
	protected TextView yuefu;
	protected TextView eryuefu;
	protected TextView jifu;
	protected TextView bannianfu;
	protected TextView nianfu;
	protected TextView yicixingfu;
	protected String fukuanfangshi = "二月付";

	private ArrayList<String> options1ItemsUse = new ArrayList<>();//租赁
	private OptionsPickerView pvOptionsUse;

	List<HeTongBean> datas;

	private String money;
	protected OnClickListener fuKuanListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
				case R.id.yuefu:
					fukuanfangshi = "月付";
					mCameraPopupWindow.dismiss();
					break;
			case R.id.eryuefu:
				fukuanfangshi = "二月付";
				mCameraPopupWindow.dismiss();
				break;
			case R.id.jifu:
				fukuanfangshi = "季付";
				mCameraPopupWindow.dismiss();
				break;
			case R.id.bannianfu:
				fukuanfangshi = "半年付";
				mCameraPopupWindow.dismiss();
				break;
			case R.id.nianfu:
				fukuanfangshi = "年付";
				mCameraPopupWindow.dismiss();
				break;
			case R.id.yicixingfu:
				fukuanfangshi = "一次性付";
				mCameraPopupWindow.dismiss();
				break;
			}
			for (int i = 0; i < editTexts.size(); i++) {
				if (editTexts.get(i).getTag().equals("pay_type")) {
					editTexts.get(i).setText(fukuanfangshi);
				}
				for (int j = 0; j < datas.size(); j++) {
					if (datas.get(j).getKey().equals("is_stage")){
						if (!fukuanfangshi.equals("月付")){//如果已经选择填了资金，如果选择的不是“月付”，资金和填写分期设为空
							zujinxinxi="";
							if (editTexts.get(i).getTag().equals("is_stage")){
								if (!editTexts.get(i).getText().toString().equals("")){
									ByAlert.alert("日期重新选择，请重新填写租金");
									if (editTexts.get(i).getTag().equals("is_stage")) {
										editTexts.get(i).setText("");
									}
								}
							}
							if (editTexts.get(i).getTag().equals("rent_info")){
								if (!editTexts.get(i).getText().toString().equals("")){
									if (editTexts.get(i).getTag().equals("rent_info")) {
										editTexts.get(i).setText("");
									}
								}
							}
						}
						break;
					}
				}
			}
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;
		case R.id.tijiao:
			long re = heTongDBManager.deleteCaoGao(uid, contractNo, "lesser");
			if (re > 0) {
				// ByAlert.alert("删除成功");
			} else {
				// ByAlert.alert("删除失败");
			}
			buildJson();// 生成json数据
			break;
		default:
			break;
		}
	}

	private void buildJson() {
		// TODO Auto-generated method stub
		HeTongDBManager deleteCaoGao = new HeTongDBManager(this);
		HashMap<String, String> map = new HashMap<String, String>();
		deleteCaoGao.deleteCaoGao(uid, contractNo, "lesser");
		for (int i = 0; i < views.size(); i++) {
			EditText editText = (EditText) views.get(i).findViewById(R.id.edit);
			if (views.get(i).getTag().equals("rent_info")) {// 房租信息
				if (zujinxinxi.equals("")){
					ByAlert.alert("请填写房租信息");
					return;
				}
				map.put(editText.getTag() + "", zujinxinxi);
			} else if (views.get(i).getTag().equals("lessor_fee_items")
					|| views.get(i).getTag().equals("renter_fee_items")
					|| views.get(i).getTag().equals("facility")) {
				TextView textView = (TextView) views.get(i).findViewById(
						R.id.txt_device);
				map.put(editText.getTag() + "", textView.getText().toString());
			} else if (views.get(i).getTag().equals("sign_leaser")) {
				if (imgId.equals("")){
					ByAlert.alert("您还没有签名");
					return;
				}
				System.out.println("签名信息" + imgId);
				map.put(editText.getTag() + "", imgId);
			}  else if (views.get(i).getTag().equals("pay_before_day")) {
				resetEdettextFocus(editText);
				EditText te = (EditText) views.get(i).findViewById(R.id.edit);
				map.put(editText.getTag() + "", te.getText().toString());
				if(te.getText().toString().equals("")) {
					ByAlert.alert("请填写下期房租提前支付天数");
					return;
				}
				if(!te.getText().toString().equals("")) {
					if (Double.parseDouble(te.getText().toString()) > 31) {
						ByAlert.alert("天数不能大于31");
						return;
					}
				}
			}else if (views.get(i).getTag().equals("is_stage")) {
				EditText te = (EditText) views.get(i).findViewById(R.id.edit);
				map.put(editText.getTag() + "", te.getText().toString().equals("是")?"1":"0");
			}else if (views.get(i).getTag().equals("is_bank_stage")) {
				EditText te = (EditText) views.get(i).findViewById(R.id.edit);
				//银行分期 样式 1年 分11期 分5*2期  半年 分5期
				if (te.getText().toString().trim().equals("是")){
					if (money.equals("合同期一年,用户分11期")||money.equals("合同期半年,用户分5期")){
						map.put(editText.getTag() + "","1");
					}else if (money.equals("合同期一年,用户半年分两次5期")){
						map.put(editText.getTag() + "","1,2");
					}
				}else {
					map.put(editText.getTag() + "","0");
				}
			}else {
				if (!views.get(i).getTag().equals("other_note")){
					EditText te = (EditText) views.get(i).findViewById(R.id.edit);
					if (te.getText().toString().equals("")) {
						ByAlert.alert("请填写详细信息");
						return;
					}
				}

				map.put(editTexts.get(i).getTag() + "", editTexts.get(i)
						.getText().toString());
			}
		}
		Gson gson = new Gson();
		String jsonStr = gson.toJson(map);
		heTongDBManager = new HeTongDBManager(this);
		long re = heTongDBManager.addNote(uid, contractNo, "lesser", jsonStr);
		if (re > 0) {
			ByAlert.alert("添加成功" + contractNo);
		} else {
			ByAlert.alert("添加失败");
		}

		userPresenter.tiJiaoHeTong(uid, contractNo, jsonStr);
		System.out.println("》》生成的json字符串" + jsonStr);
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_hetong;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		setStatusBarHeight(v_statusbar);
		add_shap_title_tv.setText("修改合同房东");
		options1ItemsUse.add("办公");
		options1ItemsUse.add("住宿");
		uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
		contractNo = getIntent().getStringExtra("contractNo");
		tijiao.setVisibility(View.GONE);
		heTongDBManager = new HeTongDBManager(this);
		String str = heTongDBManager.getCaoGaoStr(uid, contractNo, "lesser");
		if (!str.equals("")) {
			Gson gson = new Gson();
			caoGao = gson.fromJson(str, HetongCaoGao.class);
			if (caoGao != null) {
				selectDevice = caoGao.getFacility();
				selectFeiYong = caoGao.getLessor_fee_items();
				unselectFeiYong = caoGao.getRenter_fee_items();
				zujinxinxi = caoGao.getRent_info();
				imgId = caoGao.getSign_leaser();
			}
			userPresenter = new UserPresenter(this);
			userPresenter.heTongParams("0", contractNo);
		} else {
			ByAlert.alert("未查询到草稿信息");
			Intent intent=new Intent(this,TianXieHeTongActivityFangDong.class);
			intent.putExtra("contractNo", contractNo);
			startActivity(intent);
			finish();
		}

	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	String textStringStart = "";
	String textStringEnd = "";

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			Gson gson = new Gson();
			if (entity.getEventType() == UserPresenter.heTongParams_success) {
				//@SuppressWarnings("unchecked")
				datas = (List<HeTongBean>) entity.getData();
				HeTongAdapter adapter = new HeTongAdapter(this, datas,
						R.layout.item_hetong);
				Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
				for (int i = 0; i < datas.size(); i++) {
					// map2.put(datas.get(i).getAlias(), )
					HeTongBean bean = datas.get(i);
					Integer inputType = bean.getValueType();// 5、整型 1、字符串 4、日期
															// 0、点击进去 2、签字
					final View view = LayoutInflater.from(this).inflate(
							R.layout.item_hetong,null, false);
					TextView txt_device = (TextView) view
							.findViewById(R.id.txt_device);
					devices.add(txt_device);
					TextView text = (TextView) view.findViewById(R.id.txt);
					EditText editText = (EditText) view.findViewById(R.id.edit);
					switch (inputType) {// 1: 文本、2: 图片、3: 当前时间 4：当前日期 5：数字 ,默认0
					case 1:
						editText.setInputType(InputType.TYPE_CLASS_TEXT);
						break;
					case 2:

						break;
					case 3:

						break;
					case 4:

						break;
					case 5:
						editText.setInputType(InputType.TYPE_CLASS_NUMBER);
						break;

					default:
						break;
					}
					editText.setTag(bean.getKey());
					editText.setHint(bean.getDesc());
					if (!bean.get_default().equals("")) {
						editText.setEnabled(false);
						editText.setText(bean.get_default());
					}
					if (bean.getKey().equals("start_date")) {// 1
						textStringStart=caoGao.getStart_date();
						editText.setEnabled(false);
						editText.setText(caoGao.getStart_date());
					}
					if (bean.getKey().equals("end_date")) {// 2
						textStringEnd =caoGao.getEnd_date();
						editText.setEnabled(false);
						editText.setText(caoGao.getEnd_date() == null ? ""
								: caoGao.getEnd_date());
					}
					if (bean.getKey().equals("rent_info")) {// 3
						editText.setEnabled(false);
						editText.setText(caoGao.getRent_info() == null ? ""
								: "已填写");
					}
					if (bean.getKey().equals("is_bank_stage")) {// 3

						editText.setEnabled(false);
						if(caoGao.getIs_bank_stage()==null||caoGao.getIs_bank_stage().equals("")){
							view.setVisibility(View.GONE);
							editText.setText("");
						}else if (caoGao.getIs_bank_stage().equals("0")){
							view.setVisibility(View.GONE);
							editText.setText("否");
						}else {
							view.setVisibility(View.VISIBLE);
							editText.setText("是");
						}

					}
					if (bean.getKey().equals("is_stage")) {// 3
						editText.setEnabled(false);
						editText.setText(caoGao.getIs_stage() == null ? ""
								: caoGao.getIs_stage().equals("1")?"是":"否");
						if (caoGao.getIs_stage()==null||caoGao.getIs_stage().equals("")){
							view.setVisibility(View.GONE);
						}else if (caoGao.getIs_stage().equals("1")){
							view.setVisibility(View.VISIBLE);
						}else {
							view.setVisibility(View.GONE);
						}
					}
					if (bean.getKey().equals("pay_before_day")) {
						editText.setEnabled(true);
						editText.setText(caoGao.getPay_before_day() == null ? ""
								: caoGao.getPay_before_day());
					}
					if (bean.getKey().equals("sign_leaser")) {// 4
						editText.setEnabled(false);
						editText.setText(caoGao.getSign_leaser() == null ? ""
								: "已签名");
					}
					if (bean.getKey().equals("sign_leaser_year")) {// 6
						editText.setText(current.get(Calendar.YEAR) + "");
						editText.setEnabled(false);
					}
					if (bean.getKey().equals("sign_leaser_month")) {// 7
						editText.setText((current.get(Calendar.MONTH) + 1) + "");
						editText.setEnabled(false);
					}
					if (bean.getKey().equals("sign_leaser_day")) {// 8
						editText.setText(current.get(Calendar.DATE) + "");
						editText.setEnabled(false);
					}
					if (bean.getKey().equals("lesser")) {// 9
						editText.setText(caoGao.getLesser() == null ? ""
								: caoGao.getLesser());
					}
					if (bean.getKey().equals("renter")) {// 10
						editText.setText(caoGao.getRenter() == null ? ""
								: caoGao.getRenter());
					}
					if (bean.getKey().equals("address")) {// 11
						editText.setText(caoGao.getAddress() == null ? ""
								: caoGao.getAddress());
					}
					if (bean.getKey().equals("area")) {// 12
						editText.setText(caoGao.getArea() == null ? "" : caoGao
								.getArea());
					}
					if (bean.getKey().equals("id_renter")) {// 13
						editText.setText(caoGao.getId_renter() == null ? ""
								: caoGao.getId_renter());
					}
					if (bean.getKey().equals("id_leaser")) {// 14
						editText.setText(caoGao.getId_leaser() == null ? ""
								: caoGao.getId_leaser());
					}
					if (bean.getKey().equals("house_property")) {// 15
						editText.setText(caoGao.getHouse_property() == null ? ""
								: caoGao.getHouse_property());
					}
					if (bean.getKey().equals("rent_use")) {// 16
						editText.setText(caoGao.getRent_use() == null ? ""
								: caoGao.getRent_use());
					}
					if (bean.getKey().equals("max_people")) {// 17
						editText.setText(caoGao.getMax_people() == null ? ""
								: caoGao.getMax_people());
					}
					if (bean.getKey().equals("people_number")) {// 18
						resetEdettextFocus(editText);
						editText.setText(caoGao.getPeople_number() == null ? ""
								: caoGao.getPeople_number());
					}
					if (bean.getKey().equals("deposit")) {// 19
						editText.setText(caoGao.getDeposit() == null ? ""
								: caoGao.getDeposit());

					}
					if (bean.getKey().equals("pay_type")) {// 20
						editText.setEnabled(false);
						editText.setText(caoGao.getPay_type() == null ? ""
								: caoGao.getPay_type());
					}
					if (bean.getKey().equals("water_meter_reading")) {// 21
						editText.setText(caoGao.getWater_meter_reading() == null ? ""
								: caoGao.getWater_meter_reading());
					}
					if (bean.getKey().equals("gas_reading")) {// 22
						editText.setText(caoGao.getGas_reading() == null ? ""
								: caoGao.getGas_reading());
					}
					if (bean.getKey().equals("electric_instrument_reading")) {// 23
						editText.setText(caoGao
								.getElectric_instrument_reading() == null ? ""
								: caoGao.getElectric_instrument_reading());
					}
					if (bean.getKey().equals("repair_period")) {// 24
						editText.setText(caoGao.getRepair_period() == null ? ""
								: caoGao.getRepair_period());
					}
					if (bean.getKey().equals("arrears_months")) {// 25
						editText.setText(caoGao.getArrearsMonths() == null ? ""
								: caoGao.getArrearsMonths());
					}
					if (bean.getKey().equals("lessor_fee_items")) {// 26
						txt_device.setVisibility(View.VISIBLE);
						editText.setEnabled(false);
						txt_device
								.setText(caoGao.getLessor_fee_items() == null ? ""
										: caoGao.getLessor_fee_items());
					}
					if (bean.getKey().equals("renter_fee_items")) {// 27
						txt_device.setVisibility(View.VISIBLE);
						editText.setEnabled(false);
						txt_device
								.setText(caoGao.getRenter_fee_items() == null ? ""
										: caoGao.getRenter_fee_items());
					}
					if (bean.getKey().equals("facility")) {// 28
						txt_device.setVisibility(View.VISIBLE);
						editText.setEnabled(false);
						txt_device.setText(caoGao.getFacility() == null ? ""
								: caoGao.getFacility());
					}
					if (bean.getKey().equals("phone_leaser")) {// 28
						editText.setEnabled(false);
						editText.setText(caoGao.getPhone_leaser() == null ? ""
								: caoGao.getPhone_leaser());
					}
					if (bean.getKey().equals("sign_leaser_date")) {// 28
						editText.setEnabled(false);
						editText.setText(caoGao.getSign_leaser_date() == null ? ""
								: caoGao.getSign_leaser_date());
					}
					if (bean.getKey().equals("break_month")) {//违约月数

						editText.setEnabled(true);
						resetEdettextFocus(editText);
						editText.setText(caoGao.getBreak_month() == null ? ""
								: caoGao.getBreak_month());
					}
					if (bean.getKey().equals("other_note")) {//其他约定
						editText.setEnabled(true);
						resetEdettextFocus(editText);
						editText.setText(caoGao.getOther_note() == null ? ""
								: caoGao.getOther_note());
						editText.setMaxLines(3);
					}
					editTexts.add(editText);// 将所有的编辑框放进集合

					text.setText(bean.getAlias());
					li_container
							.addView(view, li_container.getChildCount() - 1);
					view.setTag(datas.get(i).getKey() + "");
					views.add(view);
					view.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							if ((v.getTag() + "").equals("facility")) {
								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityTianXieHeTongThree.class);
								startActivityForResult(intent, 101);
							}
							if ((v.getTag()+"").equals("rent_use")){//租聘用途
								EditText viewById = (EditText) v.findViewById(R.id.edit);
								initOptionPicker(viewById);
								pvOptionsUse.show();
//                                showZuPinPop(viewById);

							}
							if ((v.getTag() + "").equals("lessor_fee_items")
									|| (v.getTag() + "")
											.equals("renter_fee_items")) {
								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityFeiYongFenTan.class);
								startActivityForResult(intent, 103);
							}
							if ((v.getTag() + "").equals("sign_leaser")) {// 甲方签字
								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityHuaBan.class);
								startActivityForResult(intent, 107);//
							}
							if ((v.getTag() + "").equals("rent_info")) {
								//
								String tempDate = "";
								String tempMonth = "";
								String tempDay = "";
								for (View editText : views) {
									if (fukuanfangshi.equals("")) {
										ByAlert.alert("请先选择付款方式");
										return;
									}
									if (editText.getTag().toString()
											.equals("deposit")) {
										if (((EditText) editText
												.findViewById(R.id.edit))
												.getText().toString()
												.equals("")) {
											ByAlert.alert("请先输入预付押金");
											return;
										}
										yajin = ((EditText) editText
												.findViewById(R.id.edit))
												.getText().toString();
									}
									if (textStringEnd.equals("")
											|| textStringStart.equals("")) {
										ByAlert.alert("请先选择起租或止租日期");
										return;
									}
									if ((TimesUtils
											.getStringToDateThree(textStringEnd) - TimesUtils
											.getStringToDateThree(textStringStart)) <= 0) {
										ByAlert.alert("起租年月应小于止租年月");
										return;
									}
									if ((selectEndYear - selectStartYear) > 5) {
										ByAlert.alert("最大止租为5年");
										return;
									}

									tempDate = DayCountTwo.remainDateToString(
											textStringStart, textStringEnd);
									tempMonth = tempDate.split("-")[1];
									tempDay = tempDate.split("-")[2];
									qishu = Integer.parseInt(tempDate
											.split("-")[0]);// 获取年份
									if (fukuanfangshi.equals("二月付")) {
										if (qishu <= 0
												&& Integer.parseInt(tempMonth
														.equals("") ? "0"
														: tempMonth) < 2) {
											ByAlert.alert("付款方式为["
													+ fukuanfangshi
													+ "],租期至少为二个月");
											return;
										}
									}
									if (fukuanfangshi.equals("季付")) {
										if (qishu <= 0
												&& Integer.parseInt(tempMonth
														.equals("") ? "0"
														: tempMonth) < 4) {
											ByAlert.alert("付款方式为["
													+ fukuanfangshi
													+ "],租期至少为四个月");
											return;
										}
									}
									if (fukuanfangshi.equals("半年付")) {
										if (qishu <= 0
												&& Integer.parseInt(tempMonth
														.equals("") ? "0"
														: tempMonth) < 6) {
											ByAlert.alert("付款方式为["
													+ fukuanfangshi
													+ "],租期至少为六个月");
											return;
										}

									}
									if (fukuanfangshi.equals("年付")) {
										if (qishu <= 0) {
											ByAlert.alert("付款方式为["
													+ fukuanfangshi
													+ "],租期至少为一年");
											return;
										}

									}
									if (fukuanfangshi.equals("一次性付")) {
										if (qishu <= 0
												&& Integer.parseInt(tempMonth
														.equals("") ? "0"
														: tempMonth) < 1) {
											ByAlert.alert("付款方式为["
													+ fukuanfangshi
													+ "],租期至少为一一个月");
											return;
										}
									}
									if ((editText.getTag() + "")
											.equals("start_date")
											|| (editText.getTag() + "")
													.equals("end_date")) {
										if (((EditText) editText
												.findViewById(R.id.edit))
												.getText().toString()
												.equals("")) {
											ByAlert.alert("请选择起租或止租年月");
											return;
										} else {
											if ((editText.getTag() + "")
													.equals("start_date")) {
												tempStartTimes = ((EditText) editText
														.findViewById(R.id.edit))
														.getText().toString();
											} else {
												tempEndTimes = ((EditText) editText
														.findViewById(R.id.edit))
														.getText().toString();
											}
										}
									}
								}
								String[] startYears = tempStartTimes.split("-");
								String[] endYears = tempEndTimes.split("-");
								if ((Integer.parseInt(startYears[0])
										- (Integer.parseInt(endYears[0])) > 0)) {
									ByAlert.alert("起租年应小于止租年");
									return;
								}

								if(qishu==0){
									qishu = 1;
								}else{
									if (Integer.parseInt(tempMonth) > 0
											|| Integer.parseInt(tempDay) > 0) {
										qishu += 1;
									}
								}
								String type="1";//标记是否含有“is_stage”字段，没有type=1 表示没有分期，有type=2 表示有分期
								for (int j = 0; j < datas.size(); j++) {
									if (datas.get(j).getKey().equals("is_stage")){
										type="2";
										break;
									}
								}
								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityEditFangZuXinXi.class);
								intent.putExtra("yajin", yajin);
								intent.putExtra("qishu", qishu);
								intent.putExtra("totalDate", tempDate);
								intent.putExtra("type", type);
								intent.putExtra("contractNo", contractNo);
								startActivityForResult(intent, 105);
							}
							if ((v.getTag() + "").equals("pay_type")) {
								MyGongJv.yincang(v);
								mCameraPopupWindow = new FuKuanFangShiPopupWindow(
										ActivityEditHeTongFangdong.this, this);
								mCameraPopupWindow.showAtLocation(v,
										Gravity.BOTTOM
												| Gravity.CENTER_HORIZONTAL, 0,
										0);
								yuefu = (TextView) mCameraPopupWindow
										.getContentView().findViewById(
												R.id.yuefu);
								yuefu.setOnClickListener(fuKuanListener);
								eryuefu = (TextView) mCameraPopupWindow
										.getContentView().findViewById(
												R.id.eryuefu);
								eryuefu.setOnClickListener(fuKuanListener);
								jifu = (TextView) mCameraPopupWindow
										.getContentView().findViewById(
												R.id.jifu);
								jifu.setOnClickListener(fuKuanListener);
								bannianfu = (TextView) mCameraPopupWindow
										.getContentView().findViewById(
												R.id.bannianfu);
								bannianfu.setOnClickListener(fuKuanListener);
								nianfu = (TextView) mCameraPopupWindow
										.getContentView().findViewById(
												R.id.nianfu);
								nianfu.setOnClickListener(fuKuanListener);
								yicixingfu = (TextView) mCameraPopupWindow
										.getContentView().findViewById(
												R.id.yicixingfu);
								yicixingfu.setOnClickListener(fuKuanListener);
							}
							if ((v.getTag() + "").equals("start_date")) {
								MyGongJv.yincang(v);
								YuYueChooseTimePopwindow endTimePopwindow = new YuYueChooseTimePopwindow(
										ActivityEditHeTongFangdong.this, ActivityEditHeTongFangdong.this, true);
								endTimePopwindow.getContentView().findViewById(R.id.time).setVisibility(View.GONE);
								endTimePopwindow.getContentView().findViewById(R.id.min).setVisibility(View.GONE);
								endTimePopwindow.showAtLocation(v, Gravity.BOTTOM
										| Gravity.CENTER_HORIZONTAL, 0, 0);
							}
							if ((v.getTag() + "").equals("end_date")) {
								MyGongJv.yincang(v);
								if (textStringStart.equals("")) {
									ByAlert.alert("请先选择开始时间");
									return;
								}
								YuYueChooseTimePopwindow endTimePopwindow = new YuYueChooseTimePopwindow(
										ActivityEditHeTongFangdong.this, ActivityEditHeTongFangdong.this, false);
								endTimePopwindow.getContentView().findViewById(R.id.time).setVisibility(View.GONE);
								endTimePopwindow.getContentView().findViewById(R.id.min).setVisibility(View.GONE);
								endTimePopwindow.showAtLocation(v, Gravity.BOTTOM
										| Gravity.CENTER_HORIZONTAL, 0, 0);
							}
						}
					});

				}
				tijiao.setVisibility(View.VISIBLE);
			} else if (entity.getEventType() == UserPresenter.heTongParams_fail) {
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == UserPresenter.heTongTiJiao_success) {
				Intent intent = new Intent();
				intent.putExtra("shenfen", "lesser");
				intent.putExtra("contractNo", contractNo);
				sendBroadcast(intent);
				OrderFragment.getInstance().refresh();
				ByAlert.alert(entity.getData());
				finish();
			} else if (entity.getEventType() == UserPresenter.heTongTiJiao_fail) {
				ByAlert.alert(entity.getData());
			}
		}
	}

	//租聘用途
	private void initOptionPicker(final EditText text) {//条件选择器初始化

		/**
		 * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
		 */
        text.setFocusable(false);
		pvOptionsUse = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
			@Override
			public void onOptionsSelect(int options1, int options2, int options3, View v) {
				//返回的分别是三个级别的选中位置
				String tx = options1ItemsUse.get(options1);
				text.setText(tx);
			}
		})
				.setTitleText("租赁用途")
				.setContentTextSize(16)//设置滚轮文字大小
				.setTitleSize(16)//设置标题文字大小
				.setSubCalSize(16)//设置确定按钮大小
				.setSelectOptions(0, 1)//默认选中项
				.setLineSpacingMultiplier(2.0f)//设置间距倍数,但是只能在1.2-2.0f之间
				.setDividerColor(Color.LTGRAY)//设置分割线的颜色
				.setBgColor(Color.WHITE)//滚轮背景颜色
				.setTitleBgColor(Color.WHITE)//标题背景颜色
				.setTitleColor(Color.BLACK)//标题颜色
				.setCancelColor(Color.BLACK)//取消按钮颜色
				.setSubmitColor(Color.BLACK)//确定按钮颜色
				.setTextColorCenter(Color.BLACK)//分割线之间的文字颜色
				.isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
				.setLabels("", "", "")
				.setBackgroundId(0x66000000) //设置外部遮罩颜色
				.build();
		pvOptionsUse.setPicker(options1ItemsUse);//二级选择器
	}

	//让edittext 方便获取焦点（点击父类parentview 让edittext 获取焦点并弹出软键盘）
	public void resetEdettextFocus(EditText editText){
		editText.setFocusable(true);
		editText.setFocusableInTouchMode(true);
		editText.requestFocus();
		//打开软键盘
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 101 && resultCode == 102) {
			if (data != null) {
				selectDevice = data.getStringExtra("selectDevice");
				for (View v : views) {
					if (v.getTag().toString().equals("facility")) {
						v.findViewById(R.id.txt_device).setVisibility(
								View.VISIBLE);
						((TextView) v.findViewById(R.id.txt_device))
								.setText(selectDevice);
					}
				}
			}
		}
		if (requestCode == 103 && resultCode == 104) {
			selectFeiYong = data.getStringExtra("select");
			unselectFeiYong = data.getStringExtra("unselect");
			for (View v : views) {
				if (v.getTag().toString().equals("renter_fee_items")) {
					v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
					((TextView) v.findViewById(R.id.txt_device))
							.setText(selectFeiYong);
				}
				if (v.getTag().toString().equals("lessor_fee_items")) {
					v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
					((TextView) v.findViewById(R.id.txt_device))
							.setText(unselectFeiYong);
				}
			}
		}
		if (requestCode == 105 && resultCode == 106) {
			zujinxinxi = data.getStringExtra("zujinxinxi");
			String fenqi= data.getStringExtra("fenqi");
			String bank= data.getStringExtra("bank");
			for (View v : views) {
				if (v.getTag().toString().equals("rent_info")) {
					v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
					((EditText) v.findViewById(R.id.edit)).setText("已填写");
				}
				if (v.getTag().toString().equals("is_bank_stage")){
					v.setVisibility(View.GONE);
					((EditText) v.findViewById(R.id.edit)).setText(bank);
				}

				if (fenqi.equals("是")){ //当有分期的时候
					if (v.getTag().toString().equals("is_stage")) {
						v.setVisibility(View.VISIBLE);
						v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
						((EditText) v.findViewById(R.id.edit)).setText(fenqi);
					}
					if (v.getTag().toString().equals("pay_type")) {//当有分期的时候，付款方式默认为“月付”
						v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
						((EditText) v.findViewById(R.id.edit)).setText("月付");
					}
					if (v.getTag().toString().equals("end_date")) {//当有分期的时候，结束的月份为开始月份的一年后的前一天
						int year = Integer.parseInt(textStringStart.split("-")[0]);// 获取年份
						int mouth = Integer.parseInt(textStringStart.split("-")[1]);// 获取月份
						int day = Integer.parseInt(textStringStart.split("-")[2]);// 获取日期
						Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
						ca.set(year, mouth-1, day);//月份是从0开始的，所以11表示12月
						ca.add(Calendar.YEAR, +1);
						ca.add(Calendar.DATE, -1);
						Date lastMonth = ca.getTime(); //结果
						SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
						((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
					}
				}else {
					if (v.getTag().toString().equals("is_stage")) {
						v.setVisibility(View.GONE);
						v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
						((EditText) v.findViewById(R.id.edit)).setText(fenqi);
					}
				}
			}
		}
		if (requestCode == 105 && resultCode == 110) {  //银行分期 从租金跳转回来
			 money= data.getStringExtra("date");
			String bank= data.getStringExtra("bank");
			String fenqi= data.getStringExtra("fenqi");
			zujinxinxi = data.getStringExtra("zujinxinxi");
//            options1ItemsZhiFu.add("分11期");
//            options1ItemsZhiFu.add("分5*2期");
//            options1ItemsZhiFu.add("分5期");
//            if (zujinxinxi.equals("分11期")){
//
//            }else if (zujinxinxi.equals("分5*2期")){
//
//            }else if (zujinxinxi.equals("分5期")){
//
//            }
			for (View v : views) {
				if (v.getTag().toString().equals("is_stage")) {
					v.setVisibility(View.GONE);
					v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
					((EditText) v.findViewById(R.id.edit)).setText(fenqi);
				}

				if (v.getTag().toString().equals("rent_info")) {
					v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
					((EditText) v.findViewById(R.id.edit)).setText("已填写");
				}

//                if (v.getTag().toString().equals("is_stage")) {
//                    v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
//                    ((EditText) v.findViewById(R.id.edit)).setText("否");
//                }
				if (bank.equals("是")){  //当有分期的时候
					if (v.getTag().toString().equals("is_bank_stage")){
						v.setVisibility(View.VISIBLE);
						((EditText) v.findViewById(R.id.edit)).setText(bank);
					}
					if (v.getTag().toString().equals("pay_type")) {//当有银行分期的时候
						v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
						((EditText) v.findViewById(R.id.edit)).setText("月付");
					}

					if (v.getTag().toString().equals("end_date")) {//当有分期的时候，结束的月份为开始月份的一年后的前一天
						int startYear = Integer.parseInt(textStringStart.split("-")[0]);// 获取年份
						int startMouth = Integer.parseInt(textStringStart.split("-")[1]);// 获取月份
						int startDay = Integer.parseInt(textStringStart.split("-")[2]);// 获取日期
						int endYear = Integer.parseInt(textStringEnd.split("-")[0]);// 获取年份
						int endMouth = Integer.parseInt(textStringEnd.split("-")[1]);// 获取月份
						int endDay = Integer.parseInt(textStringEnd.split("-")[2]);// 获取日期
						if (money.equals("合同期一年,用户分11期")||money.equals("合同期一年,用户半年分两次5期")){
							Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
							ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
							ca.add(Calendar.YEAR, +1);
							ca.add(Calendar.DATE, -1);
							Date lastMonth = ca.getTime(); //结果
							SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
							((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
						}else if (money.equals("合同期半年,用户分5期")){
							Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
							ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
							ca.add(Calendar.DATE, -1);
							ca.add(Calendar.MONTH,6);//改变成6个月
							Date lastMonth = ca.getTime(); //结果
							SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
							((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
						}

//                        if (endYear>startYear){
//                            if (endMouth-startMouth>=0){//大于1年
//                                Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
//                                ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
//                                ca.add(Calendar.YEAR, +1);
//                                ca.add(Calendar.DATE, -1);
//                                Date lastMonth = ca.getTime(); //结果
//                                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//                                ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
//                            }else {//小于一年
//                                Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
//                                ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
//                                ca.add(Calendar.DATE, -1);
//                                ca.add(Calendar.MONTH,6);//改变成6个月
//                                Date lastMonth = ca.getTime(); //结果
//                                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//                                ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
//                            }
//                        }else {
//                            if (endMouth-startMouth>=5){//小于1年
//                                Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
//                                ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
//                                ca.add(Calendar.DATE, -1);
//                                ca.add(Calendar.MONTH,6);//改变成6个月
//                                Date lastMonth = ca.getTime(); //结果
//                                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//                                ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
//                            }
//
//                        }

					}
				}else {
					if (v.getTag().toString().equals("is_bank_stage")){
						v.setVisibility(View.GONE);
						((EditText) v.findViewById(R.id.edit)).setText(bank);
					}
				}
			}
		}
		if (requestCode == 107 && resultCode == 108) {// 上传签字图片
			imgId = data.getStringExtra("imgId");
			for (View v : views) {
				if (v.getTag().toString().equals("sign_leaser")) {
					v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
					((EditText) v.findViewById(R.id.edit)).setText("已签名");
				}
			}
		}

	}

	@Override
	public void getBeginTime(String year, String month, String day, String hour, String minite) {
		textStringStart = year + "-" + month + "-" + day ;
		for (View v : views) {
			if (v.getTag().toString().equals("start_date")) {
				((EditText) v
						.findViewById(R.id.edit))
						.setText(textStringStart);
				((EditText) v
						.findViewById(R.id.edit))
						.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public void getEndTime(String year, String month, String day, String hour, String minite) {
		textStringEnd = year + "-" + month + "-" + day ;
		for (View v : views) {
			if (v.getTag().toString().equals("end_date")) {
				((EditText) v
						.findViewById(R.id.edit))
						.setText(textStringEnd);
				((EditText) v
						.findViewById(R.id.edit))
						.setVisibility(View.VISIBLE);
			}
			for (int j = 0; j < datas.size(); j++) {
				if (datas.get(j).getKey().equals("is_stage")){
					int years = Integer.parseInt(textStringStart.split("-")[0]);// 获取年份
					int mouths = Integer.parseInt(textStringStart.split("-")[1]);// 获取月份
					int days = Integer.parseInt(textStringStart.split("-")[2]);// 获取日期
					Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
					ca.set(years, mouths-1, days);//月份是从0开始的，所以11表示12月
					ca.add(Calendar.YEAR, +1);
					ca.add(Calendar.DATE, -1);
					Date lastMonth = ca.getTime(); //结果
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
					String time=sf.format(lastMonth);

					int yearss = Integer.parseInt(time.split("-")[0]);// 获取年份
					int mouthss = Integer.parseInt(time.split("-")[1]);// 获取月份
					int dayss = Integer.parseInt(time.split("-")[2]);// 获取日期

					int yearsss = Integer.parseInt(year);// 获取年份
					int mouthsss = Integer.parseInt(month);// 获取月份
					int daysss = Integer.parseInt(day);// 获取日期

					System.out.println("ssssssss>"+"yearss-->"+yearss+"...mouthss"+mouthss+"...dayss"+dayss+".swr..yearsss"+yearsss+"...mouthsss"+mouthsss+"...daysss"+daysss);
					if (yearss!=yearsss||mouthss!=mouthsss||dayss!=daysss){
						zujinxinxi="";
						if (v.getTag().toString().equals("is_stage")){
							((EditText) v.findViewById(R.id.edit)).setText("");
						}
						if (v.getTag().toString().equals("rent_info")){
							((EditText) v.findViewById(R.id.edit)).setText("");
						}
					}
					break;
				}
			}
		}
	}
}
